package cn.tedu._07vehicle.filter;

import cn.tedu._07vehicle.pojo.vo.UserVO;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author tune_the last
 * @date 2025/11/19 - 9:21
 * WebFilter：配置过滤器，指定过滤器的名称和需要拦截的路径PATH
 * 1.filtername：过滤器的名称
 * 2.urlPatterns:需要拦截的路径Path，注意通配符使用一个 *
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = {"/v1/vehicle/*"})
public class LoginCheckFilter implements Filter {
    /*
        核心方法，执行具体的过滤逻辑
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.父类中使用子类的方法，需要强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //2.获取会话对象HttpSession
        HttpSession session = request.getSession();
        //3.从会话对象中获取用户标识
        UserVO userVO = (UserVO) session.getAttribute("user");
        //4.判断用户标识是否为null
        if(userVO != null){
            //放行
            filterChain.doFilter(request,response);
        }else {
            //重定向
            response.sendRedirect("/login.html");
        }
    }

    /*
        过滤器初始化的方法
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("过滤器初始化..");
    }
    /*
        过滤器销毁方法
     */
    @Override
    public void destroy() {
        log.debug("过滤器销毁...");
    }
}
